#include "SeqList.h"

void SeqListInit(SeqList* ps) {
	assert(ps);
	ps->a = (SLDateType*)malloc(sizeof(SLDateType) * 4);
	if (ps->a == NULL) {
		perror("malloc fail\n");
		exit(-1);
	}
	ps->size = 0;
	ps->capacity = 4;
}

void SeqListDestroy(SeqList* ps) {
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

void SeqListPrint(SeqList* ps) {
	assert(ps);
	for (int i = 0; i < ps->size; ++i) {
		printf("%d->", ps->a[i]);
	}
	printf("\n");
}

void SLcheckCapacity(SeqList* ps) {
	assert(ps);
	if (ps->size == ps->capacity) {
		SLDateType* tmp = (SLDateType*)realloc(ps->a, sizeof(SLDateType) * 2 * ps->capacity);
		if (tmp == NULL) {
			perror("malloc fail\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
}


void SeqListPushBack(SeqList* ps, SLDateType x) {
	assert(ps);
	SLcheckCapacity(ps);
	ps->a[ps->size] = x;
	ps->size++;
}


void SeqListPushFront(SeqList* ps, SLDateType x) {
	assert(ps);
	SLcheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= 0) {
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}

void SeqListPopBack(SeqList* ps) {
	assert(ps->size > 0);
	ps->size--;
}

void SeqListPopFront(SeqList* ps) {
	assert(ps);
	int begin = 1;
	while (begin < ps->size) {
		ps->a[begin - 1] = ps->a[begin];
		++begin;
	}
	ps->size--;
}

int SeqListFind(SeqList* ps, SLDateType x) {
	assert(ps);
	for (int i = 0; i < ps->size; ++i) {
		if (ps->a[i] == x)
			return i;
	}
	return -1;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x) {
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLcheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= pos) {
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[pos] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos) {
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	int begin = pos + 1;
	while (begin < ps->size) {
		ps->a[begin - 1] = ps->a[begin];
		++begin;
	}
	ps->size--;
}



